%%% ------------------------------------------------------------------
%%% Licensed under the Apache License, Version 2.0 (the 'License');
%%%  you may not use this file except in compliance with the License.
%%%  You may obtain a copy of the License at
%%%
%%%      http://www.apache.org/licenses/LICENSE-2.0
%%%
%%% Copyright (c) 2014-2017 dwg <bypf2009@vip.qq.com>
%%%
%%%  Unless required by applicable law or agreed to in writing, software
%%%  distributed under the License is distributed on an 'AS IS' BASIS,
%%%  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%%  See the License for the specific language governing permissions and
%%%  limitations under the License.
%%%
%%% @doc  调用gun发送请求
%%% @author  dwg <'bypf2009@vip.qq.com'>
%%% @copyright 2014-2017 dwg <bypf2009@vip.qq.com>
%%% @end
%%% created|changed : 2017-02-09 16:55
%%% coding : utf-8
%%% ------------------------------------------------------------------
-module(mguns).
-author("dwg").

-export ([gun_get/1, gun_post/2]).
-export ([gun_get_wait/2, gun_post_wait/3]).

-include ("domain.hrl").

%%@doc
gun_get(Path) ->
	{ok, #{
        dnsserver := DNSServer,
        protocol := Protocol,
        port := Port
    }} = application:get_env(domain, config),
	{ok, Pid} = gun:open(DNSServer, Port, #{protocols => [Protocol]}),
	Response = gun_get_wait(Pid, "/?" ++ Path),
	gun:close(Pid),
	Response.

gun_post(Path, Data) ->
	{ok, #{
        dnsserver := DNSServer,
        protocol := Protocol,
        port := Port
    }} = application:get_env(domain, config),
	{ok, Pid} = gun:open(DNSServer, Port, #{protocols => [Protocol]}),
	Response = gun_post_wait(Pid, Path, Data),
	gun:close(Pid),
	Response.

%%@doc 发送GET请求，同时获取返回结果
-spec gun_get_wait(ConnPid, Path) -> {Status, RespHeaders, Body} when
			ConnPid :: pid(),
			Path    :: string(),
			Status  :: non_neg_integer(),
			RespHeaders :: maps:map(),
			Body    :: binary() .
gun_get_wait(ConnPid, Path) ->
	Ref = gun:get(ConnPid, Path),
	case gun:await(ConnPid, Ref) of
		{response, nofin, Status, RespHeaders} ->
			{ok, Body} = gun:await_body(ConnPid, Ref),
			gun:flush(Ref),
			{Status, RespHeaders, Body};
		{response, fin, Status, RespHeaders} ->
			gun:flush(Ref),
			{Status, RespHeaders, <<>>};
		UnExpect ->
			gun:flush(Ref),
			UnExpect
	end.

%%@doc 发送POST请求，同时获取返回结果
-spec gun_post_wait(ConnPid, Path, Data) -> {Status, RespHeaders, Body} when
			ConnPid :: pid(),
			Path    :: string(),
			Data    :: binary(),
			Status  :: non_neg_integer(),
			RespHeaders :: maps:map(),
			Body    :: binary() .
gun_post_wait(ConnPid, Path, Data) ->
	Ref = gun:post(ConnPid, Path, ?POST_HEADERS, Data),
	case gun:await(ConnPid, Ref, ?GUN_TIMEOUT) of
		{response, nofin, Status, RespHeaders} ->
			{ok, Body} = gun:await_body(ConnPid, Ref),
			{Status, RespHeaders, Body};
		{response, fin, Status, RespHeaders} ->
			{Status, RespHeaders, <<>>};
		UnExpect ->
			gun:flush(Ref),
			UnExpect
	end.
